import logging
import time, datetime

from logging import handlers
import yaml

class Logger():
    def __init__(self, fileName=None, level=None, tag="normal"):
        level = self.setLogLevel() if not level else level
        logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                            level=level)
        if not fileName:
            fileLogPath = f'Logs/local.{tag}_{time.strftime("%Y-%m-%d", time.localtime())}.log'
            errorLogPath = f'Logs/err.local.{tag}_{time.strftime("%Y-%m-%d", time.localtime())}.log"'
        else:
            fileLogPath = f"Logs/{fileName}.log"
            errorLogPath = f'Logs/err_{fileName}.{time.strftime("%Y-%m-%d", time.localtime())}.log'
        
        log_format = '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s'
        fileLog = handlers.RotatingFileHandler(fileLogPath, mode='a', maxBytes=1024 * 1024 * 10, backupCount=7, encoding="utf-8", delay=0)
        fileLog.setLevel(level=level)
        fileLog.setFormatter(logging.Formatter(log_format))

        errorLog = logging.FileHandler(errorLogPath, mode='a')
        errorLog.setLevel(level=logging.ERROR)
        errorLog.setFormatter(logging.Formatter(log_format))

        self.logger = logging.getLogger(fileLogPath)
        self.logger.addHandler(fileLog)
        # if not self.logger.hasHandlers():
        #     self.logger.addHandler(fileLog)
        # self.logger = logging.getLogger(errorLogPath)
        # if not self.logger.hasHandlers():
        #     self.logger.addHandler(errorLog)
        
    def setLogLevel(self):
        with open('conf/settings.conf', 'r', encoding='utf-8') as f:
            setting = yaml.load(f.read(), Loader=yaml.FullLoader)
        loggingLevel = setting.get('env', 'DEBUG')
        if loggingLevel == 'DEBUG':
            level = logging.DEBUG
        else:
            level = logging.INFO

        return level
        